{% extends "PC/template.html" %}

{% block title %}
AI 智能问答
{% endblock %}

{% block css %}
<style>
    .public-flex-3 {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
    }

    .chat-container {
        max-height: 300px;
        /* 设置最大高度 */
        overflow-y: auto;
        /* 垂直方向自动显示滚动条 */
        overflow-x: hidden;
        /* 隐藏水平滚动条 */
        margin: 0 auto;
        padding: 20px;
    }

    .message-item {
        display: flex;
        margin-bottom: 20px;
        width: 100%;
    }

    .message-item.user {
        justify-content: flex-end;
    }

    .message-content {
        max-width: 70%;
        padding: 12px 16px;
        border-radius: 8px;
        position: relative;
        word-wrap: break-word;
    }

    .message-item .avatar {
        width: 40px;
        height: 40px;
        margin: 0 10px;
    }

    .message-item .avatar img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
    }

    .message-content {
        display: flex;
        flex-wrap: wrap;
    }

    .message-item.ai .message-content {
        background-color: #f0f0f0;
        color: #333;
        margin-left: 10px;
    }

    .message-item.ai .message-content::before {
        content: '';
        position: absolute;
        left: -10px;
        top: 12px;
        border: 6px solid transparent;
        border-right-color: #f0f0f0;
    }

    .message-item.user .message-content {
        background-color: #409EFF;
        color: white;
        margin-right: 10px;
    }

    .message-item.user .message-content::after {
        content: '';
        position: absolute;
        right: -10px;
        top: 12px;
        border: 6px solid transparent;
        border-left-color: #409EFF;
    }
</style>
<style>
    .panel {
        border: 1px solid #ccc;
        border-radius: 4px;
        margin-bottom: 10px;
    }

    .panel-header {
        padding: 10px;
        background-color: #f0f0f0;
        cursor: pointer;
        font-size: 14px;
    }

    .panel-content {
        padding: 10px;
        font-size: 14px;
        color: #a0a0a0;
        display: block;
        /* 默认展开 */
    }
</style>
<style>
    .chat-box {
        width: 100%;
        margin: 20px auto;
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    }

    .message-area {
        padding: 16px;
        border-bottom: 1px solid #f0f0f0;
    }

    .prompt {
        color: #666;
        font-size: 14px;
        line-height: 1.4;
    }

    .input-wrapper {
        display: flex;
        align-items: center;
        padding: 12px;
    }
</style>
<style>
    .message-input {
        margin: 10px;
        border-top: 1px solid #eee;
    }
</style>
{% endblock %}

{% block content %}
<div class="layui-panel">
    <div style="padding: 15px;">
        <button type="button" class="layui-btn layui-btn-sm " lay-on="createNewChat">
            创建新对话
            <i class="layui-icon layui-icon-addition"></i>
        </button>
    </div>
</div>

<div style="padding: 15px;">
    <div class="layui-card layui-panel">
        <div class="layui-card-header public-flex-3">
            <div>
                <span>当前模型: </span>
                <span id="currentModel"></span>
            </div>
            <div class="layui-form">
                <select lay-filter="AiModelSelect" id="AiModelSelect">
                    <option value="">你的模型</option>
                    <!-- <optgroup label="腾讯元宝">
                        <option value="hunyuan_gpt_175B_0404">hunyuan(基础)</option>
                        <option value="deep_seek_v3">deep_seek_v3(基础)</option>
                        <option value="hunyuan_t1">hunyuanT1(深度思考)</option>
                        <option value="deep_seek">deep_seek(深度思考)</option>
                    </optgroup> -->

                </select>
            </div>
        </div>
        <div class="layui-card-body">
            <div class="chat-container">
                <!-- <div class="message-item ai">
                    <div class="avatar">
                        <img src="https://c-ssl.dtstatic.com/uploads/blog/202303/20/20230320145706_07ca5.thumb.400_0.jpeg"
                            alt="头像">
                    </div>
                    <div class="message-content">
                                      <div class="panel">
        <div class="panel-header" onclick="togglePanel(this)">深度思考中... (点击展开、收缩)</div>
        <div class="panel-content">
                                    ${data.content}
                                </div>
                            </div>
                        <p>你好，我是AI机器人，有什么可以帮你的吗？</p>
                    </div>
                </div> -->
                <!--
                <div class="message-item user">
                    <div class="message-content">
                        <p>你好，我想问一个问题</p>
                    </div>
                    <div class="avatar">
                        <img src="https://c-ssl.dtstatic.com/uploads/blog/202303/20/20230320145706_07ca5.thumb.400_0.jpeg"
                            alt="头像">
                    </div>
                </div> -->


            </div>

        </div>
    </div>

</div>

<div class="message-input">


    <div class="chat-box">
        <div class="message-area">
        </div>
        <div class="input-wrapper">
            <textarea class="layui-textarea" placeholder="输入消息..."
                style="flex: 1; margin-right: 10px; resize: none; height: 100px;"></textarea>
            <button class="layui-btn layui-btn-normal layui-btn-radius" lay-on="send">
                <i class="layui-icon layui-icon-release"></i> 发送
            </button>
        </div>
    </div>


</div>


<div class="layui-footer">
    <!-- 底部固定区域 -->
    <span class="layui-font-green">由简单小队开发，当前是1.0.3版本，后面会继续完善并出更多的创意功能，欢迎联系我，一起交流</span>
  </div>



{% endblock %}

{% block js %}

<script>
    // 模型平台
    let model_platform = '';
    // 当前对话ID
    let current_chat_id = '';
    // 当前对话名称
    let current_chat_name = '';
    // 当前对话模型
    let current_model = '';

    // 模型
    let model_list = [];
</script>

<script>



    // 自动滚动到底部函数
    function scrollToBottom() {
        var chatContainer = document.querySelector('.chat-container');
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }
</script>
<script>
    function togglePanel(header) {
        const content = header.nextElementSibling;
        if (content.style.display === 'none') {
            content.style.display = 'block';
        } else {
            content.style.display = 'none';
        }
    }
</script>
<script>
    layui.use(function () {
        var element = layui.element;
        var layer = layui.layer;
        var form = layui.form;
        var util = layui.util;
        var $ = layui.jquery;
        element.render('nav');
       
        // 加载模型
        function loadModel() {
            const model_api = '/api/TengXunYuanBao/get_model/';
            axios({
                method: 'get',
                url: model_api,
            }).then(res => {
                if (res.status == 200) {
                    let AiModelSelect = document.querySelector('#AiModelSelect');
                    model_list = res.data;
                    res.data.forEach(item => {
                        // console.log(item);
                        let option_group = document.createElement('optgroup');
                        option_group.label = item.name;
                        item.model.forEach(model => {
                            let option = document.createElement('option');
                            option.value = model.value;
                            option.innerHTML = model.name;
                            option_group.appendChild(option);
                            console.log(option);
                        });
                        AiModelSelect.appendChild(option_group);
                    });
                }
                form.render('select');
            }).catch(err => {
                console.log(err);
            })
        }
        
        loadModel()
        // 函数
        // 用户信息
        function UserMessage(message) {
            if (current_chat_id == '') {
                layer.msg('请先创建新对话');
                return;
            }
            $('.layui-textarea').val('');

            // 用原生JS向chat-container添加用户信息
            var chatContainer = document.querySelector('.chat-container');
            var messageItem = document.createElement('div');
            var avatar = document.createElement('div');
            avatar.classList.add('avatar');
            avatar.innerHTML = '<img src="https://c-ssl.dtstatic.com/uploads/blog/202303/20/20230320145706_07ca5.thumb.400_0.jpeg" alt="头像">';
            messageItem.classList.add('message-item', 'user');
            messageItem.innerHTML = '<div class="message-content">' + message + '</div> <div class="avatar">' + avatar.innerHTML + '</div>';
            chatContainer.appendChild(messageItem);
            scrollToBottom();

            // 创建 EventSource 连接
            const url = `/api/${model_platform}/JiChuBan/send_message/?chat_id=${current_chat_id}&message=${message}&model=${current_model}`;
            const eventSource = new EventSource(url);
            let robot_message_timestamp = RobotMessage("正在思考...");
            // 定义一个变量代表第一次创建
            let first_create = false;
            eventSource.onmessage = (event) => {
                scrollToBottom();
                let data = JSON.parse(event.data);
                console.log(data);

                if (data.type == 'text') {
                    console.log(data.msg);
                    let new_p = document.createElement('p');
                    new_p.innerHTML = data.msg;
                    let messageItem = document.querySelector('.' + robot_message_timestamp + ' .message-content');
                    messageItem.appendChild(new_p);
                } else if (data.type == 'end') {
                    eventSource.close();

                } else if (data.type == 'think') {
                    console.log("思考中: " + data.content);
                    if (first_create == false) {
                        console.log("本次回答存储元素", robot_message_timestamp, document.querySelector('.' + robot_message_timestamp + ' .message-content'));

                        document.querySelector('.' + robot_message_timestamp + ' .message-content').innerHTML = `
                        
                           <div class="panel">
        <div class="panel-header" onclick="togglePanel(this)">深度思考中... (点击展开、收缩)</div>
        <div class="panel-content">
                                    ${data.content}
                                </div>
                            </div>
                        `;



                    }
                    else {
                        let new_collapse_content_span = document.createElement('span');
                        new_collapse_content_span.innerHTML = data.content;
                        document.querySelector('.' + robot_message_timestamp + ' .panel-content ').appendChild(new_collapse_content_span);
                    }
                }

                if (first_create == false) {
                    document.querySelector('.' + robot_message_timestamp + ' .message-content').innerHTML = document.querySelector('.' + robot_message_timestamp + ' .message-content').innerHTML.replace('正在思考...', '');
                    first_create = true;
                }
            }

            eventSource.onerror = (error) => {
                console.error('EventSource failed:', error);
                eventSource.close();
                throw new Error('流式请求失败');
            };
        }
        // 机器人信息
        function RobotMessage(message) {
            // 生成当前时间戳
            let timestamp = 'message-item-' + new Date().getTime();

            // 用原生JS向chat-container添加机器人信息
            var chatContainer = document.querySelector('.chat-container');
            var messageItem = document.createElement('div');
            messageItem.classList.add('message-item', 'ai', timestamp);
            var avatar = document.createElement('div');
            avatar.classList.add('avatar');
            avatar.innerHTML = '<img src="https://c-ssl.dtstatic.com/uploads/blog/202303/20/20230320145706_07ca5.thumb.400_0.jpeg" alt="头像">';
            messageItem.innerHTML = '<div class="avatar">' + avatar.innerHTML + '</div><div class="message-content">' + message + '</div> ';
            chatContainer.appendChild(messageItem);
            return timestamp;
        }



        // 工具模型的选择返回
        function toolModelSelect(value) {
            model_list.forEach(item => {
                item.model.forEach(model => {
                    if (model.value == value) {
                        model_platform = item.platform;
                    }
                });
            });

        }


        form.on('select(AiModelSelect)', function (data) {
            var value = data.value; // 获得被选中的值
            current_model = value;
            layer.msg(`已切换到 ${this.innerHTML} 模型`); // this 为当前选中 <option> 元素对象
            $('#currentModel').text(this.innerHTML);
            toolModelSelect(value);
        });
        util.on('lay-on', {
            send: function () {
                var message = $('.layui-textarea').val();
                // 判断message是否为空
                if (message == '') {
                    layer.msg('请输入消息');
                    return;
                }

                // 发送消息
                UserMessage(message);



                console.log('发送消息', message);
            },

            createNewChat: function () {
                const new_chat_api = `/api/${model_platform}/JiChuBan/create_new_chat/`;
                axios({
                    method: 'get',
                    url: new_chat_api,

                }).then(res => {
                    if (res.status == 200) {
                        current_chat_id = res.data.id;
                        layer.msg('创建新对话成功');
                    }
                }).catch(err => {
                    layer.msg("模型平台错误");
                    console.log(err);
                })
            }
        });


    });
</script>

{% endblock %}